package development.app.mxh;

import java.util.Vector;

import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.TouchScreenListener;
import state.component.BottomBar;
import state.component.Event;
import state.component.EventListener;
import state.component.GameMenu;
import state.component.GameScrollBar;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.Hashtable;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.group.FrmGroupKetBanMangXHChat;
import development.socket.ProtocolConstants;

public class FrmMessage extends GameForm implements EventListener, TouchScreenListener {

  private static GameForm singleton;
  private ImageText text8;
  private String type;
  private int dy;

  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView;
  private GameMenu menu;
  private int messageStart;
  private int messageEnd;

  private Vector messages;
  private int messageIndex;

  private int packageNumber;
  private int totalPackage;
  private int percent;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmMessage();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    type = "list_message";
    messageStart = 0;
    messageEnd = 5;
    dy = DrawUtils.getTopBarHeight();
    packageNumber = 0;
    totalPackage = 0;
    percent = 0;
    messages = new Vector();
    messageIndex = 0;
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10);
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);

    menu = new GameMenu(null, new String[] { "Xem", "Xóa tin nhắn", "Xóa TN đã đọc", "Xóa toàn bộ TN", "Menu MXH" }, 5, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    BottomBar bottomBar = DrawUtils.getBottomBar(_manager);
    bottomBar.setLabels("Menu", "Chọn", "Trở về");
    bottomBar.setLeftMenu("Menu", menu);
    _manager.enableTouchPad();

    DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.MESSAGE_LIST_REQUEST);
    dataPackage.putInt(messageStart);
    dataPackage.putInt(messageEnd);
    Global.authenClient.write(dataPackage);
    new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR).setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        DrawUtils.drawTopBar(g);
        if (type.equals("view_message")) {
          Message message = (Message) messages.elementAt(messageIndex);
          String title = message.title;
          if (title == null || title.equals("")) {
            title = "Không tiêu đề";
          }
          text8.drawString2(g, title, GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
        }
        if (type.equals("reply_message")) {
          text8.drawString2(g, "Gửi tin nhắn", GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
        }
        if (type.equals("list_message")) {
          if (messages == null || messages.isEmpty()) {
            text8.drawString2(g, "Tin nhắn(0)", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
          } else {
            text8.drawString2(g, "Tin nhắn(" + messages.size() + ")", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
          }
        }
      }
    }).setSize(Constants.SCREEN_WIDTH, 25);
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (type.equals("list_message")) {
      drawMessageList(g);
    }
    if (type.equals("view_message")) {
      drawViewMessage(g);
    }
    DrawUtils.drawTopBar(g);
    drawMenu(g);
  }

  private void drawMenu(Graphics g) {
    if (percent > 0 && percent < 100) {
      DrawUtils.getBottomBar(_manager).setCenterLabel(percent + "%");
    }
    if (type.equals("list_message")) {
      DrawUtils.getBottomBar(_manager).setLabels("Menu", "Chọn", "Trở về");
      DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menu);
    }
    if (type.equals("view_message")) {
      DrawUtils.getBottomBar(_manager).setLabels("", "Trả lời", "Trở về");
    }
  }

  private void drawViewMessage(Graphics g) {
    int textY = dy;
    Message message = (Message) messages.elementAt(messageIndex);
    text8.drawParagraph2(g, message.content, GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH, DEFAULT_TEXT_X, textY, scrollBar);
  }

  private void drawMessageList(Graphics g) {
    int textY = dy;
    for (int i = 0; i < messages.size(); i++) {
      Message message = (Message) messages.elementAt(i);
      if (messageIndex == i) {
        g.setColor(0x53A4CF);
        g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, Global.getDefaultAvatar().getHeight());
      }
      GameImage avatar = Global.getAvatar(message.sender);
      g.drawImage(avatar, 0, textY, GameConstants.TOP_LEFT_ANCHOR);
      text8.setBold(true);
      text8.drawString3(g, message.title, GameColor.YELLOW_CODE, avatar.getWidth() + 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      text8.setBold(false);
      textY = textY + 20;
      text8.drawString3(g, "Gửi: " + message.messageTime, GameColor.YELLOW_CODE, avatar.getWidth() + 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + Global.getDefaultAvatar().getHeight() - 20;
      g.setColor(0xC0C0C0);
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    type = mapDataPackage.popString("type");
    switch (header) {
    case ProtocolConstants.ResponseHeader.MESSAGE_LIST_RESPOSNE:
      Global.systemCanvas.hideAlert();
      Message message = new Message();
      message.id = mapDataPackage.getString("id");
      message.title = mapDataPackage.getString("title");
      int index = message.title.indexOf("RE:");
      if (index >= 0) {
        message.title.substring(index, message.title.length());
      }
      message.content = mapDataPackage.getString("content");
      message.sender = mapDataPackage.getString("sender");
      message.recipient = mapDataPackage.getString("recipient");
      message.messageTime = mapDataPackage.getString("messageTime");
      message.status = mapDataPackage.getString("status");
      message.totalMessage = mapDataPackage.getInt("totalMessage");
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      messages.addElement(message);
      break;
    case ProtocolConstants.ResponseHeader.MESSAGE_DELETE_READ_RESPONSE:
      removeReadMessage();
      break;
    case ProtocolConstants.ResponseHeader.MESSAGE_DELETE_ALL_RESPONSE:
      messages.removeAllElements();
      break;
    case ProtocolConstants.ResponseHeader.MESSAGE_DELETE_RESPONSE:
      messages.removeElementAt(messageIndex);
      break;
    default:
      break;
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.RIGHT:
      if (type.equals("list_message")) {
        Message message = (Message) messages.elementAt(0);
        if (messageEnd >= message.totalMessage) {
          return;
        }
        if ((messageEnd + 5) > message.totalMessage) {
          messageEnd = message.totalMessage;
          messageStart = messageEnd - 5;
        } else {
          messageStart += 5;
          messageEnd += 5;
        }
        DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.MESSAGE_LIST_REQUEST);
        dataPackage.putInt(messageStart);
        dataPackage.putInt(messageEnd);
        Global.authenClient.write(dataPackage);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        messageIndex = 0;
        if (messages != null) {
          messages.removeAllElements();
        }
      }
      break;
    case Key.LEFT:
      if (type.equals("list_message")) {
        if (messageStart <= 0) {
          return;
        }
        messageStart -= 5;
        messageEnd -= 5;
        if (messageStart < 0) {
          messageStart = 0;
          messageEnd = 5;
        }
        DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.MESSAGE_LIST_REQUEST);
        dataPackage.putInt(messageStart);
        dataPackage.putInt(messageEnd);
        Global.authenClient.write(dataPackage);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        messageIndex = 0;
        if (messages != null) {
          messages.removeAllElements();
        }
      }
      break;
    case Key.SOFT_LEFT:
      break;
    case Key.SOFT_RIGHT:
      if (type.equals("list_message")) {
        Global.nextState(FrmGroupKetBanMangXHChat.instance(), null);
      }
      if (type.equals("view_message")) {
        type = "list_message";
      }
      break;
    case Key.DOWN:
      if (type.equals("list_message")) {
        if (messageIndex < messages.size() - 1) {
          messageIndex++;
        }
        if (messages.size() * (Global.getDefaultAvatar().getHeight()) < GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight()) {
          return;
        }
        if (scrollBar.canScrollUp()) {
          dy = dy - (Global.getDefaultAvatar().getHeight());
        }
      }
      break;
    case Key.UP:
      if (type.equals("list_message")) {
        if (messageIndex > 0) {
          messageIndex--;
        }
        if (scrollBar.canScrollDown()) {
          dy = dy + (Global.getDefaultAvatar().getHeight());
        }
      }
      break;
    case Key.FIRE:
      if (type.equals("view_message")) {
        Message message = (Message) messages.elementAt(messageIndex);
        Hashtable parameters = new Hashtable();
        parameters.put("User", message.sender);
        FrmSendMessage.backForm = this;
        Global.nextState(FrmSendMessage.instance(), parameters);
      }
      if (type.equals("list_message")) {
        type = "view_message";
        Message message = (Message) messages.elementAt(messageIndex);
        message.status = "1";
        DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.VIEW_MESSAGE_REQUEST);
        dataPackage.putString(message.id);
        Global.authenClient.write(dataPackage);
      }
      break;
    default:
      break;
    }
  }

  public void onActionPerform(Event event) {
    String action = event.getAction();
    if (action.equals("Menu MXH")) {
      FrmGroupKetBanMangXHChat.tabIndex = 1;
      Global.nextState(FrmGroupKetBanMangXHChat.instance(), null);
    } else if (action.equals("Xóa TN đã đọc")) {
      Global.alert.showAlert2(this, GameAlert.YES_NO_TYPE, "Bạn có chắc chắn?", 50);
    } else if (action.equals("Xóa tin nhắn")) {
      Global.alert.showAlert2(this, GameAlert.YES_NO_TYPE, "Bạn có chắc chắn?", 51);
    } else if (action.equals("Xóa toàn bộ TN")) {
      Global.alert.showAlert2(this, GameAlert.YES_NO_TYPE, "Bạn có chắc chắn?", 52);
    } else if (action.equals("Xem")) {
      if (!messages.isEmpty()) {
        type = "view_message";
      }
    } else if (action.equals("Trả lời")) {
      Message message = (Message) messages.elementAt(messageIndex);
      Hashtable parameters = new Hashtable();
      parameters.put("User", message.sender);
      Global.nextState(FrmSendMessage.instance(), parameters);
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 50 && eventType == GameAlert.YES_BUTTON) {
      DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.MESSAGE_DELETE_READ_REQUEST);
      Global.authenClient.write(dataPackage);
    } else if (alertId == 51 && eventType == GameAlert.YES_BUTTON) {
      Message message = (Message) messages.elementAt(messageIndex);
      DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.MESSAGE_DELETE_REQUEST);
      dataPackage.putString(message.id);
      Global.authenClient.write(dataPackage);
    } else if (alertId == 52 && eventType == GameAlert.YES_BUTTON) {
      DataPackage dataPackage = DataPackage.createDataPackage1(ProtocolConstants.RequestHeader.MESSAGE_DELETE_ALL_REQUEST);
      Global.authenClient.write(dataPackage);
    }
  }

  private void removeReadMessage() {
    int index = 0;
    while (index < messages.size()) {
      Message message = (Message) messages.elementAt(index);
      if (message.status.equals("1")) {
        messages.removeElementAt(index);
        continue;
      }
      index++;
    }
  }

  public void pointerDragged(Sprite source, int x, int y) {
  }

  public void pointerPressed(Sprite source, int x, int y) {
  }

  public void pointerReleased(Sprite source, int x, int y) {
  }

  public void destroy() {
    text8 = null;
    type = null;

    scrollBar = null;
    textView = null;
    menu = null;
    messages = null;
  }

  private class Message {
    public String id;
    public String title;
    public String content;
    public String sender;
    public String recipient;
    public String messageTime;
    public String status;
    public int totalMessage;
  }
}
